package com.yueya.basic.role.service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.yueya.basic.menu.Menu;
import com.yueya.basic.role.model.RoleMenu;
import com.yueya.common.model.Tree;
import com.yueya.common.util.UUIDGenerator;

/**
 * 
 * @author yangfeng 角色和菜单关联表
 * 
 */
public class RoleMenuService {

	/**
	 * 获取菜单树
	 * 
	 * @param id
	 * @return
	 */
	public List<Tree> getTreeRoleMenu(String id) {
		List<RoleMenu> list = RoleMenu.dao.getListByRoleId(id);
		// List<Tree> treeList = Menu.service.toTree();

		List<Tree> treeList = new ArrayList<Tree>();
		treeList.add(Menu.service.recursiveTree("000"));
		parseTree(treeList, list);
		return treeList;
	}

	private void parseTree(List<Tree> list, List<RoleMenu> checkedList) {
		for (Tree temp : list) {
			for (RoleMenu t : checkedList) {
				if (t.get("menu_id").equals(temp.getId()))
					temp.setChecked(true);
			}
			if (temp.getChildren() != null)
				parseTree(temp.getChildren(), checkedList);
		}
	}

	/**
	 * 先删除roleid关联的菜单，再添加
	 * 
	 * @param roleid
	 * @param userids
	 * @return
	 */
	@Before(Tx.class)
	public boolean saveRoleMenus(String roleid, String[] menuids) {
		RoleMenu rm = null;
		//RoleMenu rm1 = null;
		// 删除
		RoleMenu.dao.deleteByRoleId(roleid);

		boolean bl = false;
		if (menuids != null && menuids.length > 0) {
			//String sql = "select * from t_role_menu where role_id = ? and menu_id = ?";
			for (int i = 0; i < menuids.length; i++) {

//				Menu m = Menu.dao.findById(menuids[i]);
//				rm1 = RoleMenu.dao.findFirst(sql, roleid, m.getStr("parent_id"));
//				if (rm1 == null) {
//					rm = new RoleMenu();
//					rm.set("id", UUIDGenerator.getUUID());
//					rm.set("role_id", roleid);
//					rm.set("menu_id", m.getStr("parent_id"));
//					bl = rm.save();
//				}

				rm = new RoleMenu();
				rm.set("id", UUIDGenerator.getUUID());
				rm.set("role_id", roleid);
				rm.set("menu_id", menuids[i]);
				bl = rm.save();
			}
		}
		return bl;

	}

}
